import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:short_video_app/utils/color_util.dart';
import 'package:short_video_app/view_model/main/main_view_model.dart';

class MainPage extends StatefulWidget {
  const MainPage({Key? key}) : super(key: key);

  @override
  _MainPageState createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (BuildContext context) => MainViewModel(),
      child: Consumer<MainViewModel>(builder: (context, viewModel, child) {
        return Scaffold(
          body: IndexedStack(
            index: viewModel.currentIndex,
            /// 底部 TabBar 对应的页面
            children: viewModel.pages,
          ),
          /// 底部导航栏
          bottomNavigationBar: BottomAppBar(
            shape: const CircularNotchedRectangle(),
            notchMargin: 5.0,
            color: ColorsUtil.COLOR_FFFFFF,
            child: Padding(
              padding: const EdgeInsets.only(top: 10),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: viewModel.pages.asMap().keys.map((index) => _buildBottomBarItem(context, viewModel, selectIndex: viewModel.currentIndex, itemIndex: index, iconName: viewModel.iconPaths[index], title: viewModel.titles[index])).toList(),
              ),
            ),
          ),
          /// 悬浮按钮，发布
          floatingActionButton: FloatingActionButton(
            backgroundColor: ColorsUtil.COLOR_FFFFFF,
            child: Image.asset("assets/png/tabbar/publish_active.png", width: 32, gaplessPlayback: true),
            onPressed: () {
              viewModel.toPublishPage(context);
            }
          ),
          floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        );
      }),
    );

  }

  /// 底部导航按钮
  Widget _buildBottomBarItem(BuildContext context, MainViewModel viewModel, {
    required int selectIndex,
    required int itemIndex,
    String? iconName,
    String? title,
  }) {
    bool isSelected = selectIndex == itemIndex;

    return GestureDetector(
      child: SizedBox(
        height: kBottomNavigationBarHeight,
        child: Column(
          children: [
            Image.asset(isSelected ? "assets/png/tabbar/${iconName}_active.png" : "assets/png/tabbar/$iconName.png", width: 32, gaplessPlayback: true),
            const SizedBox(height: 4),
            Text(title ?? "", style: TextStyle(fontSize: 14, color: isSelected ? ColorsUtil.COLOR_FF5C5C : ColorsUtil.COLOR_999999),)
          ],
        ),
      ),
      behavior: HitTestBehavior.opaque,
      onTap: () {
        /// 如果该页面未被选中
        if (!isSelected) {
          viewModel.switchPage(context, iconName ?? "");
        }
      },
    );
  }
}
